<?php

class DB extends Base
{
    protected $connectionString, $user, $password;
    protected $error;
    protected $connection;

    public function __construct($connectionString,$user,$password)
    {
        $this->connectionString=$connectionString;
        $this->user=$user;
        $this->password=$password;

        $this->connection=$this->connect();
    }

    public function query($sql,$class=null)
    {
        if($class===null) $class='stdClass';
        try{
            $result=array();
            $request=$this->connection->query($sql);
            $res=$request->setFetchMode(PDO::FETCH_CLASS,$class);

            if(!strpos($sql,'NSERT ') && !strpos($sql,'PDATE ') && !strpos($sql,'EPLACE ')){
                while($row=$request->fetch()){
                    $result[]=$row;
                }
                return $result;
            }else{
                return $res;
            }
        }catch(PDOException $e) {
            if(Sys::app()->config->mode=='test') die('Ошбка выполнения запроса: '.$e->getMessage());
            else Sys::app()->error='Ошбка выполнения запроса: '.$e->getMessage();
        }
        return false;
    }

    protected function getDbName()
    {
        $arrayOfConnectionString=array_filter(explode('=',Sys::app()->db->connectionString));
        return end($arrayOfConnectionString);
    }

    private function connect()
    {
        try{
            $link=new PDO($this->connectionString,$this->user,$this->password);
            if(Sys::app()->config->mode=='test') $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            else $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

            return $link;
        }catch(PDOException $e) {
            if(Sys::app()->config->mode=='test') die('Ошибка подключения к БД: '.$e->getMessage());
            else Sys::app()->error='Ошибка подключения к БД: '.$e->getMessage();
        }

        return false;
    }
}